//
//  ShopMapViewController.m
//  BaseFrame
//
//  Created by 孟学浩 on 2017/5/18.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "ShopMapViewController.h"
#import "Annotation.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "ButWhatMapView.h"
#import "KCCalloutAnnotationView.h"

#define ROUND_WIDTH 30

@interface ShopMapViewController () <MKMapViewDelegate,CLLocationManagerDelegate>
{
    CLLocationManager *_locationManager;
   
    CLLocationCoordinate2D centerCoordinate;
    NSString *longitude;
    NSString *latitude;
}

@property CLLocationDegrees latitudeDelta;

@property (nonatomic , strong) UIButton *theCurrentPosition;                        /**<当前位置*/
@property (nonatomic , strong) MKMapView *mapView;

@property (nonatomic , strong) UIBarButtonItem *theNextStepBarButton;               //下一步
@property (nonatomic , strong) CLGeocoder *geocoder;                                /**<地理编码*/
@property (nonatomic ,strong)  Annotation *annotation1;


@end

//网络
@implementation ShopMapViewController (NetWorking)

- (void)getData:(NSString *)address{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"s_id":[UserModel sharedInstanced].s_id,
                                 @"s_address":address,
                                 @"s_longitude":longitude,
                                 @"s_latitude":latitude};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Store_Mobile/modifyStoreAddress.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        ShowMessage(responseObject[@"msg"]);
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            [UserModel sharedInstanced].latitude = latitude;
            [UserModel sharedInstanced].longitude = longitude;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

@end

@implementation ShopMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"搜索店铺";
    [self.view addSubview:self.mapView];
    [[ButWhatMapView sharedInstanced]startUpdatingLocation:^{
        
    }];
    self.navigationItem.rightBarButtonItem = self.theNextStepBarButton;
    _locationManager = [[CLLocationManager alloc]init];
    
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
        NSLog(@">>>>>>>>>> 位置服务不可用 <<<<<<<<<<<<");
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的位置服务当前不可用，请打开位置服务后重试" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
    if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        [_locationManager requestWhenInUseAuthorization];
    }
    _locationManager.delegate = self;
    //     设置定位精度
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
}

//点击地图事件

- (void)mTapPress:(UIGestureRecognizer*)gestureRecognizer {
    
    CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];//这里touchPoint是点击的某点在地图控件中的位置
    
    CLLocationCoordinate2D touchMapCoordinate = [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];//这里touchMapCoordinate就是该点的经纬度了
    
    
    NSLog(@"touching %f,%f",touchMapCoordinate.latitude,touchMapCoordinate.longitude);
    latitude = [NSString stringWithFormat:@"%f",touchMapCoordinate.latitude];
    longitude = [NSString stringWithFormat:@"%f",touchMapCoordinate.longitude];
    CLLocationCoordinate2D location1 = CLLocationCoordinate2DMake(touchMapCoordinate.latitude, touchMapCoordinate.longitude);
    self.annotation1.coordinate = location1;
//    annotation1.title = @"救援1";
//    annotation1.subtitle = @"good";
    [_mapView addAnnotation:self.annotation1];
    
}

#pragma mark - init

- (Annotation *)annotation1{
    if (!_annotation1) {
        _annotation1 = [[Annotation alloc]init];
    }
    return _annotation1;
}

- (CLGeocoder *)geocoder
{
    if (!_geocoder) {
        self.geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}


/**
 *  地图初始化
 */
- (MKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 44)];
        _mapView.delegate = self;
        [_mapView addSubview:self.theCurrentPosition];
        _mapView.userTrackingMode = MKUserTrackingModeFollow;
        _mapView.mapType = MKMapTypeStandard;
        //是否显示交通流量
                _mapView.showsTraffic =YES;
        //旋转地图时是否显示指南针
                _mapView.showsCompass =YES;
        //是否在地图上显示比例尺
                _mapView.showsScale =YES;
        UITapGestureRecognizer *mTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mTapPress:)];
        
        [_mapView addGestureRecognizer:mTap];
    }
    return _mapView;
}

/**
 *  当前位置按钮初始化
 */
- (UIButton *)theCurrentPosition{
    if (!_theCurrentPosition) {
        _theCurrentPosition = [[UIButton alloc]initWithFrame:CGRectMake(10 / WIDTH_5S_SCALE, SCREEN_HEIGHT - 100 / WIDTH_5S_SCALE - 64, 40 / WIDTH_5S_SCALE, 40 / WIDTH_5S_SCALE)];
        [_theCurrentPosition setImage:[UIImage imageNamed:@"location"] forState:UIControlStateNormal];
        [_theCurrentPosition addTarget:self action:@selector(theCurrentPositionClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return  _theCurrentPosition;
}

#pragma mark - click

/**
 *  当前位置点击事件
 */
- (void)theCurrentPositionClick{
    NSLog(@"当前位置");
    [_locationManager startUpdatingLocation];
}

#pragma mark 选中大头针时触发
//点击一般的大头针KCAnnotation时添加一个大头针作为所点大头针的弹出详情视图
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
    Annotation * annotation= view.annotation;
    if ([view.annotation isKindOfClass:[Annotation class]])
    {
        //点击一个大头针时移除其他弹出详情视图
        //        [self removeCustomAnnotation];
        //添加详情大头针，渲染此大头针视图时将此模型对象赋值给自定义大头针视图完成自动布局
        KCCalloutAnnotation *annotation1=[[KCCalloutAnnotation alloc]init];
        annotation1.coordinate=view.annotation.coordinate;
        [mapView addAnnotation:annotation1];
    }
}

#pragma mark - Mapview delegate

//设置大头针样式
-(MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    //由于当前位置的标注也是一个大头针，所以此时需要判断，此代理方法返回nil使用默认大头针视图
//    static NSString *key1=@"AnnotationKey1";
//    MKAnnotationView *annotationView=[_mapView dequeueReusableAnnotationViewWithIdentifier:key1];
//    //如果缓存池中不存在则新建
//    if (!annotationView) {
//        annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:key1];
//        annotationView.canShowCallout = YES;//允许交互点击
//        //            annotationView.calloutOffset = CGPointMake(0, 1);//定义详情视图偏移量
//        //            annotationView.leftCalloutAccessoryView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_classify_cafe.png"]];//定义详情左侧视图
//    }
    
    if ([annotation isKindOfClass:[Annotation class]])
    {
        MKAnnotationView *annotationView = [_mapView dequeueReusableAnnotationViewWithIdentifier:NSStringFromClass([Annotation class])];
        if (!annotationView)
        {
            annotationView = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:NSStringFromClass([Annotation class])];
            //            annotationView.canShowCallout = true;
            annotationView.calloutOffset = CGPointMake(0, 1);
        }
        annotationView.annotation = annotation;
        annotationView.image = [UIImage imageNamed:@"icon_location"];
        return annotationView;
    }
    else if([annotation isKindOfClass:[KCCalloutAnnotation class]])
    {
        //对于作为弹出详情视图的自定义大头针视图无弹出交互功能（canShowCallout=false，这是默认值），在其中可以自由添加其他视图（因为它本身继承于UIView）
        KCCalloutAnnotationView *calloutView = [KCCalloutAnnotationView calloutViewWithMapView:mapView];
        calloutView.getCalloutAnnotationClick = ^(NSString *str) {
            if ([[UserModel sharedInstanced].s_id isEqualToString:@""]) {
                ShowMessage(@"请先创建店铺");
                return ;
            }
            UIAlertController *av = [UIAlertController alertControllerWithTitle:@"确定修改店铺地址？" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self getData:str];
            }];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [av addAction:action1];
            [av addAction:action2];
            [self presentViewController:av animated:YES completion:nil];
        };
        calloutView.annotation = annotation;
        return calloutView;
    }

    return nil;
    //修改大头针视图
    //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
//    annotationView.annotation = annotation;
//    annotationView.image = [[UIImage alloc]init];//设置大头针视图的图片
//    annotationView.image.accessibilityFrame = CGRectMake(0, 0, 20 / WIDTH_5S_SCALE, 20 / WIDTH_5S_SCALE);
//    return annotationView;
    
}

#pragma mark - CLLocationManager delegate
//定位触发
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    
    NSLog(@"经度%f,纬度%f",newLocation.coordinate.longitude, newLocation.coordinate.latitude);
    
    if(self.mapView.userTrackingMode != MKUserTrackingModeFollow)
    {
        [self.mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
    }
    
    //取消定位
    [manager stopUpdatingLocation];
    
}

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
    [self removeCustomAnnotation];
}

- (void)removeCustomAnnotation
{
    [_mapView.annotations enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj isKindOfClass:[KCCalloutAnnotation class]]) {
            [_mapView removeAnnotation:obj];
        }
    }];
}

////显示地图改变发生触发
//- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
//    MKCoordinateRegion region;
//    centerCoordinate = mapView.region.center;
//    region.center= centerCoordinate;
//    NSLog(@" 中心店位置 -- %f,%f",centerCoordinate.latitude, centerCoordinate.longitude);
//}

@end
